<template>
  <div class="app-container rebate-rules">
    <el-row class="header-wrap" justify="space-between" align="middle">
      <div>{{ businessLevelName }}</div>
      <el-button @click="back">返回上一页</el-button>
    </el-row>
    <el-row class="row-bg" justify="space-between" align="middle">
      <el-radio-group v-model="queryGrade.gradeType" @change="gradeTypeChange">
        <el-radio value="1" size="large">未设置({{ levelCount.unsetCount }})</el-radio>
        <el-radio value="2" size="large">续约设置({{ levelCount.unsetRenewCount }})</el-radio>
        <el-radio value="3" size="large">已设置</el-radio>
      </el-radio-group>
      <div>
        <el-input
          v-model="queryGrade.factoryName"
          placeholder="请输入工厂名称"
          suffix-icon="Search"
          clearable
          style="width: 240px"
        />
        <el-button type="primary" icon="Search" @click="searchData" style="margin-left: 10px">查询</el-button>
        <el-button plain icon="Refresh" @click="reset" style="margin-left: 10px">重置</el-button>
      </div>
    </el-row>
    <!-- 未设置、已设置列表 -->
    <template v-if="queryGrade.gradeType == 1 || queryGrade.gradeType == 3">
      <el-table v-loading="loading" :data="gradeTable" highlight-current-row style="width: 100%; margin-top: 20px">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column property="factoryName" label="工厂名称" min-width="250" />
        <el-table-column v-if="queryGrade.gradeType == 1" property="status" label="工厂返佣状态" width="120">
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.status === 0">未设置</el-tag>
            <el-tag type="primary" v-else-if="scope.row.status === 3">已开启</el-tag>
            <el-tag type="warning" v-else>{{
              scope.row.status === 2 ? "待开启" : scope.row.status === 1 ? "待审批" : "续约中"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="queryGrade.gradeType != 1" property="settingBy" label="设置人" width="120" />
        <el-table-column v-if="queryGrade.gradeType != 1" property="settingTime" label="设置日期" />
        <el-table-column v-if="queryGrade.gradeType != 1" property="updateBy" label="更新人" />
        <el-table-column v-if="queryGrade.gradeType != 1" property="updateBy" label="更新日期" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button v-if="scope.row.status === 0 || scope.row.status === 1" link type="info" disabled>
              设置商家返佣
            </el-button>
            <el-button v-else link type="primary" @click="openBusinessDrawer(scope.row)">
              {{ queryGrade.gradeType == 1 ? "设置商家返佣" : "管理商家返佣" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 签约设置列表 -->
    <template v-if="queryGrade.gradeType == 2">
      <el-table v-loading="loading" :data="gradeTable" highlight-current-row style="width: 100%; margin-top: 20px">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column property="factoryName" label="工厂名称" />
        <el-table-column property="startTime" label="续约开始时间" width="400" />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" @click="openBusinessDrawer(scope.row)"> 更新商家返佣 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <pagination :total="listTotal" v-model:page="queryGrade.current" v-model:limit="queryGrade.size" @pagination="searchData" />

    <!-- 商家抽屉 -->
    <business-drawer
      v-if="isBusinessDrawer"
      :renewalDrawer="isBusinessDrawer"
      :title="queryGrade.gradeType == 1 || queryGrade.gradeType == 3 ? '设置商家返佣' : '更新商家返佣'"
      :isEdit="isEdit"
      :businessFormData="businessFormData"
      @closeDeawerEmits="renewalDrawerChang"
      @businessInfoSubmit="businessInfoSubmit"
      @openreRenewalDrawer="openreRenewalDrawer"
    ></business-drawer>

    <!-- 详情里点击查看续约---抽屉 -->
    <business-drawer
      v-if="isUpBusinessDrawer"
      :renewalDrawer="isUpBusinessDrawer"
      :title="'更新商家返佣'"
      :isEdit="isUpBusinessEdit"
      :businessFormData="businessRenewalFormData"
      @closeDeawerEmits="isUpBusinessDrawerClose"
      @businessInfoSubmit="isUpBusinessInfoSubmit"
    ></business-drawer>
  </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import businessDrawer from "./components/businessDrawer.vue";
import {
  pageList,
  businessLevelCount,
  settingDetail,
  settingSubmit,
  renewPage,
  renewDetail,
  renewSubmit,
  alreadySetPage,
  alreadySetDetail,
  alreadySetEdit
} from "@/api/system/rebateRules/businessGrade";
const router = useRouter();
const route = useRoute();
const businessLevelName = ref(route.query.businessLevelName);
// 商家搜索条件
const queryGrade = ref({
  gradeType: "1",
  factoryName: "",
  businessLevelId: route.query.businessLevelId,
  current: 1,
  size: 10
});
// 商家表格
const gradeTable = ref([]);
// 商家表格总数
const listTotal = ref(0);
// 返回上一页
const back = () => {
  router.go(-1);
};
// 等级单选变化
const gradeTypeChange = value => {
  queryGrade.value = {
    gradeType: queryGrade.value.gradeType,
    factoryName: queryGrade.value.factoryName,
    businessLevelId: route.query.businessLevelId,
    current: 1,
    size: 10
  };
  searchData();
};

// 已设置列表分页
const getAlreadySetPage = () => {
  loading.value = true;
  alreadySetPage(queryGrade.value).then(res => {
    gradeTable.value = res.data.list;
    listTotal.value = res.data.total;
    loading.value = false;
  });
};

// 续约设置列表分页
const getRenewPage = () => {
  loading.value = true;
  renewPage(queryGrade.value).then(res => {
    gradeTable.value = res.data.list;
    listTotal.value = res.data.total;
    levelCount.value.unsetRenewCount = res.data.total;
    loading.value = false;
  });
};

// 搜索
const searchData = () => {
  let value = queryGrade.value.gradeType;
  if (value == 1) {
    getTable(queryGrade.value);
  } else if (value == 2) {
    getRenewPage(queryGrade.value);
  } else {
    getAlreadySetPage(queryGrade.value);
  }
};

// 重置
const reset = () => {
  queryGrade.value = {
    gradeType: queryGrade.value.gradeType,
    factoryName: "",
    businessLevelId: route.query.businessLevelId,
    current: 1,
    size: 10
  };
  searchData();
};

// 商家抽屉是否弹出
const isBusinessDrawer = ref(false);
const isEdit = ref(true);
const businessFormData = ref({});
// 打开商家抽屉
const openBusinessDrawer = row => {
  isBusinessDrawer.value = true;
  isEdit.value = true;
  if (queryGrade.value.gradeType == 1) {
    let query = {
      businessLevelId: row.businessLevelId,
      factoryCommissionId: row.factoryCommissionId
    };
    getSettingDetail(query);
  } else if (queryGrade.value.gradeType == 2) {
    let query = {
      businessLevelId: row.businessLevelId,
      renewFactoryCommissionId: row.renewFactoryCommissionId
    };
    getRenewDetail(query);
  } else {
    isEdit.value = false;
    let query = {
      businessLevelCommissionId: row.businessLevelCommissionId
    };
    getAlreadySetDetail(query);
  }
};

// 查询已设置详情
const getAlreadySetDetail = query => {
  businessFormData.value.isLoading = true;
  alreadySetDetail(query).then(res => {
    res.data.businessLevelId = res.data.businessLevelId || 1;
    res.data.businessCommissionRatios?.forEach(item => {
      item.amount = Number(item.amount);
      item.factoryCommissionRatio = Number(item.factoryCommissionRatio);
      item.businessLevelCommissionRatio = Number(item.businessCommissionRatio);
    });
    businessFormData.value = res.data;
    businessFormData.value.businessFormTable = res.data.businessCommissionRatios;
    businessFormData.value.businessAfterFormTable = res.data.renewBusinessLevelCommissionRatios;
    businessFormData.value.isSetRenew = businessFormData.value.hasRenew;
    businessFormData.value.hasRenew = false;
    businessFormData.value.isLoading = false;
    businessFormData.value.buttonLoading = false;
  });
};

// 查询续约设置详情
const getRenewDetail = query => {
  businessFormData.value.isLoading = true;
  renewDetail(query).then(res => {
    res.data.businessCommissionRatios?.forEach(item => {
      item.amount = Number(item.amount);
      item.factoryCommissionRatio = Number(item.factoryCommissionRatio);
      item.businessRatio = Number(item.businessCommissionRatio);
    });
    res.data.renewFactoryCommissionRatios?.forEach(item => {
      item.amount = Number(item.amount);
      item.factoryCommissionRatio = Number(item.factoryCommissionRatio);
    });
    businessFormData.value = res.data;
    businessFormData.value.businessFormTable = res.data.businessCommissionRatios;
    businessFormData.value.businessAfterFormTable = res.data.renewFactoryCommissionRatios;
    businessFormData.value.hasRenew = true;
    businessFormData.value.isLoading = false;
    businessFormData.value.buttonLoading = false;
  });
};

// 查询未设置详情
const getSettingDetail = query => {
  businessFormData.value.isLoading = true;
  settingDetail(query).then(res => {
    res.data.factoryCommissionRatios?.forEach(item => {
      item.amount = Number(item.amount);
      item.factoryCommissionRatio = Number(item.factoryCommissionRatio);
    });
    res.data.renewFactoryCommissionRatios?.forEach(item => {
      item.amount = Number(item.amount);
      item.factoryCommissionRatio = Number(item.factoryCommissionRatio);
    });
    businessFormData.value = res.data;
    businessFormData.value.businessFormTable = res.data.factoryCommissionRatios;
    businessFormData.value.businessAfterFormTable = res.data.renewFactoryCommissionRatios;
    businessFormData.value.isLoading = false;
    businessFormData.value.buttonLoading = false;
  });
};

// 抽屉 确认
const businessInfoSubmit = dataValue => {
  if (queryGrade.value.gradeType == 1) {
    businessSettingSubmit(dataValue);
  } else if (queryGrade.value.gradeType == 2) {
    businessUpSubmit(dataValue);
  } else if (queryGrade.value.gradeType == 3) {
    let postData = {
      businessLevelCommissionId: businessFormData.value.businessLevelCommissionId,
      businessLevelCommissionRatios: businessFormData.value.businessFormTable
    };
    editSetRenew(businessFormData, postData);
  }
};

// 续约设置提交
const businessUpSubmit = dataValue => {
  let businessAfterFormTable = businessFormData.value.businessAfterFormTable;
  let arfterRatioJudge = businessAfterFormTable.every(item => item.businessLevelCommissionRatio > 0);
  if (!arfterRatioJudge) {
    ElMessage.error("请输入对应等级商家返点");
    return;
  }
  // 返点比例，判断下一阶梯返点比例必须>上一级,
  if (businessAfterFormTable.length > 1) {
    for (let i = 0; i < businessAfterFormTable.length; i++) {
      let ratio = businessAfterFormTable[i].businessLevelCommissionRatio;
      if (i > 0) {
        if (ratio < businessAfterFormTable[i - 1].businessLevelCommissionRatio) {
          ElMessage.error("对应等级商家返点输入错误");
          return;
        }
      }
    }
  }

  businessFormData.value.buttonLoading = true;
  businessFormData.value.renewBusinessLevelCommissionRatios = businessFormData.value.businessAfterFormTable;
  renewSubmit(businessFormData.value).then(res => {
    isBusinessDrawer.value = false;
    ElMessage.success("设置成功");
    searchData();
  });
};

// 未设置提交
const businessSettingSubmit = dataValue => {
  let businessFormTable = businessFormData.value.businessFormTable;
  let ratioJudge = businessFormTable.every(item => item.businessLevelCommissionRatio > 0);
  if (!ratioJudge) {
    ElMessage.error("请输入对应等级商家返点");
    return;
  }

  // 返点比例多条数据，判断下一阶梯返点比例必须>上一级,
  if (businessFormTable.length > 1) {
    for (let i = 0; i < businessFormTable.length; i++) {
      let ratio = businessFormTable[i].businessLevelCommissionRatio;
      if (i > 0) {
        if (ratio <= businessFormTable[i - 1].businessLevelCommissionRatio) {
          ElMessage.error("对应等级商家返点输入错误");
          return;
        }
      }
    }
  }

  let businessAfterFormTable = businessFormData.value.businessAfterFormTable;
  if (businessAfterFormTable) {
    let arfterRatioJudge = businessAfterFormTable.every(item => item.businessLevelCommissionRatio > 0);
    if (!arfterRatioJudge) {
      ElMessage.error("请输入对应等级商家返点");
      return;
    }
    // 返点比例，判断下一阶梯返点比例必须>上一级,
    if (businessAfterFormTable.length > 1) {
      for (let i = 0; i < businessAfterFormTable.length; i++) {
        let ratio = businessAfterFormTable[i].businessLevelCommissionRatio;
        if (i > 0) {
          if (ratio < businessAfterFormTable[i - 1].businessLevelCommissionRatio) {
            ElMessage.error("对应等级商家返点输入错误");
            return;
          }
        }
      }
    }
  }
  businessFormData.value.buttonLoading = true;
  businessFormData.value.businessLevelCommissionRatios = businessFormData.value.factoryCommissionRatios;
  businessFormData.value.renewBusinessLevelCommissionRatios = businessFormData.value.businessAfterFormTable;
  settingSubmit(businessFormData.value).then(res => {
    isBusinessDrawer.value = false;
    ElMessage.success("设置成功");
    searchData();
  });
};

// 已设置-编辑提交（返佣比例/续约后比例提交）
const editSetRenew = (data, postData) => {
  alreadySetEdit(postData)
    .then(res => {
      isBusinessDrawer.value = false;
      isUpBusinessDrawer.value = false;
      data.value.buttonLoading = false;
      ElMessage.success("编辑成功");
      searchData();
    })
    .catch(err => {
      data.value.buttonLoading = false;
    });
};

// 关闭商家抽屉
const renewalDrawerChang = value => {
  isBusinessDrawer.value = value;
};

// 详情里点击查看续约比例---抽屉
const isUpBusinessDrawer = ref(false);
const isUpBusinessEdit = ref(true);
const businessRenewalFormData = ref({});
const openreRenewalDrawer = row => {
  isUpBusinessDrawer.value = true;
  isUpBusinessEdit.value = false;

  businessRenewalFormData.value = { ...businessFormData.value };
  businessRenewalFormData.value.businessFormTable?.forEach(item => {
    item.businessRatio = item.businessLevelCommissionRatio;
  });
  businessRenewalFormData.value.businessAfterFormTable?.forEach(item => {
    item.amount = Number(item.amount);
    item.factoryCommissionRatio = Number(item.factoryCommissionRatio);
    item.businessLevelCommissionRatio = Number(item.businessCommissionRatio);
  });
  businessRenewalFormData.value.isSetRenew = false;
  businessRenewalFormData.value.hasRenew = true;
};

// 详情里点击查看续约---抽屉--提交
const isUpBusinessInfoSubmit = value => {
  // 单独商家--续约调整判断
  let businessAfterFormTable = businessRenewalFormData.value.businessAfterFormTable;
  let arfterRatioJudge = businessAfterFormTable.every(item => item.businessLevelCommissionRatio > 0);
  if (!arfterRatioJudge) {
    ElMessage.error("请输入对应等级商家返点");
    return;
  }
  // 返点比例，判断下一阶梯返点比例必须>=上一级,
  if (businessAfterFormTable.length > 1) {
    for (let i = 0; i < businessAfterFormTable.length; i++) {
      let ratio = businessAfterFormTable[i].businessLevelCommissionRatio;
      if (i > 0) {
        if (ratio < businessAfterFormTable[i - 1].businessLevelCommissionRatio) {
          ElMessage.error("对应等级商家返点输入错误");
          return;
        }
      }
    }
  }
  businessRenewalFormData.value.renewRatios = businessRenewalFormData.value.businessAfterFormTable;
  businessRenewalFormData.value.buttonLoading = true;
  let postData = {
    businessLevelCommissionId: businessRenewalFormData.value.renewBusinessLevelCommissionId,
    businessLevelCommissionRatios: businessRenewalFormData.value.businessAfterFormTable
  };
  editSetRenew(businessRenewalFormData, postData);
};
// 详情里点击查看续约---抽屉--取消
const isUpBusinessDrawerClose = value => {
  isUpBusinessDrawer.value = value;
};

const loading = ref(false);

const levelCount = ref({
  unsetCount: 0,
  unsetRenewCount: 0
});
// 获取商家等级下 未设置、续约调整的总数
const getBusinessLevelCount = () => {
  console.log(queryGrade.value.businessLevelId);
  businessLevelCount(queryGrade.value.businessLevelId).then(res => {
    levelCount.value = res.data;
  });
};

// 获取表格数据
const getTable = () => {
  loading.value = true;
  pageList(queryGrade.value).then(res => {
    gradeTable.value = res.data.list;
    listTotal.value = res.data.total;
    levelCount.value.unsetCount = res.data.total;
    loading.value = false;
  });
};

onMounted(() => {
  getTable();
  getBusinessLevelCount();
});
</script>
<style lang="scss" scoped>
.header-wrap {
  border-bottom: 1px solid #e1effe;
  padding-bottom: 20px;
}
.row-bg {
  margin-top: 20px;
}
</style>
